/**
 * Created by Dalyn on 2017/3/28.
 */
import React from "react";
import Relay from "react-relay";
import getGoodsCatalogMutation from "./mutation/GetGoodsCatalogMutation"
import GetGoodsListMutation from "./mutation/GetGoodsListMutation"
import {hashHistory} from 'react-router';
import {Modal,Table} from "antd";
import Confirm from "../../common/Confirm"
import InputBox from "../../common/InputBox"
import ReactKey from "../../util/ReactKey"
import Util from "../../util/Util"
import BatchHint from "./BatchHint";
import "./css/product.css";
import Product_item from "./Product_item"
import ProductBomb from "./ProductBomb"
import ProductEdit from "./ProductEdit"
import Pagination from "./Pagination"
import DeleteGoodsMutation from "./mutation/DeleteGoodsMutation";
import AllGoodsPropertyMapper from "./mutation/AllGoodsPropertyMapper";

export default class Product extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            /*参数*/
            level: "1",
            token: "",
            name: "",
            levelId: "0",
            /*产品id*/
            productId: "0",
            parenId: "",
            /*产品字段*/
            goodsProperty: "",
            goodsInfoDescModelList: [],

            /*一级分类*/
            firstLevel: [],
            /*二级分类*/
            secondLevel: [],

            /*产品信息参数*/
            categoryId: "13",
            /*请求参数错误提示*/
            hint: "",
            /*操作成功提示*/
            successHint: true,
            pageSize: "10",
            loading:true,
            pageNum:"1",

            /*总条数*/
            totalResult:"",
            selectedRowKeys:"",
            selectedRows:[],
        };
        this.categoryId="0";
        this.categoryIdSender="13";
        this.defaultSecondId = "0";

        /*当前页条数*/
        this.pageItem="";
        /*页码*/
       // this.pageNum=1;
        /*每页条数*/
        this.pageSize=10;

        /*一级选中*/
        this.isFirst=0;
        /*二级选中*/
        this.isSecond=0;
        /**
         * 选中的产品ids
         *
         */
        this.productIds="";

        this.productName="";

        this.checkedFlag = false;
        this.ratio = "";
        this.dayRate = "";
        this.style = {
            confirm1: {
                width: '85px',
                height: '30px',
                backgroundColor: "#36b3b3",
                fontSize: "14px",
                color: "#fff",
                // marginTop: "16px",
                marginLeft: "20px",
                fontFamily: "Microsoft YaHei",
                borderRadius: "30px"
            },
            confirm2: {
                width: '85px',
                height: '30px',
                backgroundColor: "transparent",
                fontSize: "14px",
                color: "#4c5e70",
                // marginTop: "16px",
                marginLeft: "20px",
                fontFamily: "Microsoft YaHei",
                borderRadius: "30px"
            },
            search: {
                width: '85px',
                height: '30px',
                backgroundColor: "#36b3b3",
                fontSize: "16px",
                color: "#fff",
                // marginTop: "16px",
                marginLeft: "20px",
                fontFamily: "Microsoft YaHei",
                borderRadius: "8px"
            },
            set: {
                width: '60px',
                height: '27px',
                backgroundColor: "#fab955",
                fontSize: "16px",
                color: "#fff",
                fontFamily: "Microsoft YaHei",
                borderRadius: "3px",
                marginLeft: "15px"
            },
            batchEditing: {
                width: '100px',
                height: '30px',
                backgroundColor: "#36b3b3",
                fontSize: "14px",
                color: "#fff",
                fontFamily: "Microsoft YaHei",
                borderRadius: "2px",
                marginLeft: "15px"
                // marginTop: "6px"
            },
            page_ensure: {
                width: '40px',
                height: '22px',
                lineHeight:"22px",
                fontSize: "12px",
                color: "#999",
                fontFamily: "Microsoft YaHei",
                backgroundColor: "transparent",
                border:"1px solid #ededed",
                borderRadius: "2px",
                marginLeft: "10px",
            }
        };
        /*this.propertyMapper = {
            productName:"品名",
            styleNo:"款号",
            constituent:"成分及含量",
            specification:"规格",
            gramWeight:"克重",
            larghezza:"幅宽",
            description:"描述",
            ranzhengProcess:"染整工艺",
            yarn:"纱支",
            fabricWeave:"织物组织",
            density:"密度",
            season:"适用季节",
            purpose:"用途",
            carding:"梳棉工艺",
            networkType:"成网方式",
            thickness:"厚度",
            weftYarn:"经纬编",
            high:"毛高",
            weavingProcess:"织造工艺",
            colour:"颜色",
            size:"尺码",
            prickle:"单位",
            yarnTypes:"纱线类型",
            yarnState:"成纱状态",
        };*/
        this.propertyMapper = {};
        /**
         * 商品类型id与名的映射
         */
        this.categoryMapper={};
        this.ischoseid = [];
        this.companyId=sessionStorage.getItem("enterpriseId");
        this.messageFlag = true;
    }
    /*分类请求*/
    levelRelay(categoryId,level) {
        Relay.Store.commitUpdate(
            new getGoodsCatalogMutation({
                categoryId:categoryId,
                level:level
            }),
            {
                onFailure: () => {
                    console.log("请求失败")
                },
                onSuccess: (response) => {
                    let errorCode = response.getGoodsCatalog.responseData.errorCode;
                    let goodsCataLogSecond = [];
                    if(errorCode==0){
                        if (categoryId!=undefined && categoryId !=0){
                            goodsCataLogSecond = response.getGoodsCatalog.responseData.goodsInfoCatalogModelList;
                            this.setCategoryMapper(goodsCataLogSecond);
                            this.setState({
                                secondLevel:goodsCataLogSecond
                            });
                            this.categoryIdSender = goodsCataLogSecond[0].categoryId;
                            this.productInfoRelay(this.categoryIdSender);
                            return;
                        }
                        let goodsCatalog = response.getGoodsCatalog.responseData.goodsInfoCatalogModelList;
                        this.setCategoryMapper(goodsCatalog);
                        this.setState({
                            firstLevel:goodsCatalog
                        });
                        this.categoryIdSender = goodsCatalog[0].categoryId;
                        this.productInfoRelay(this.categoryIdSender);
                    }else if (level == 1){
                        this.productInfoRelay(this.categoryIdSender);
                        this.setState({
                            secondLevel:[],
                        });
                        this.isSecond=0;
                    }
                }

            }
        );
    }
    /*产品信息请求*/
    productInfoRelay(categoryIdSender) {
        Relay.Store.commitUpdate(
            new GetGoodsListMutation({
                pageSize: this.pageSize,
                pageNum: this.state.pageNum,
                categoryId: categoryIdSender,
                productName: this.productName,
                goodsId: this.state.productId,
                companyId: this.companyId,
            }),
            {
                onFailure: () => {
                    console.log("请求失败")
                },
                onSuccess: (response) => {
                    // alert(this.categoryId);
                    let data = response.getGoodsList.responseData;
                    if (data.errorCode === "0") {
                        this.pageItem = data.goodsInfoDescModelList?data.goodsInfoDescModelList.length:[];
                        this.setState({
                            totalResult:data.totalResult,
                            goodsProperty: data.goodsProperty?data.goodsProperty:"",
                            goodsInfoDescModelList: data.goodsInfoDescModelList?data.goodsInfoDescModelList:[],
                            selectedRowKeys:[],
                            selectedRows:[],
                            loading:false,
                        });
                        this.refs.pagination.setState({
                            text:this.state.pageNum,
                        })
                    } else {
                        this.setState({
                            hint: data.value,
                            loading:false,
                            goodsProperty: data.goodsProperty?data.goodsProperty:"",
                            goodsInfoDescModelList:[]
                        });
                    }
                    // this.refs._selectAll.checked = false;
                }

            }
        );
    }
    /*删除商品*/
    doDeleteProduct(){
        let {selectedRowKeys} = this.state;
        Relay.Store.commitUpdate(
            new DeleteGoodsMutation({
                ids: selectedRowKeys.join(","),
            }),
            {
                onFailure: () => {
                    console.log("请求失败")
                },
                onSuccess: (response) => {
                    let data = response.deleteGoods.responseData;
                    if (data.errorCode === "0") {
                        // this.pageInit();
                        let this_ = this;
                        Util.messageHint(this_,"info","删除成功");
                        this.setState({
                            pageNum:this.refs.pagination.state.text,
                        },this.productInfoRelay(this.categoryIdSender));
                    } else {
                        if(data.errorCode != 9999){
                            let this_ = this;
                            Util.messageHint(this_,"info",data.value);
                        }
                    }
                }

            }
        );
    }
    /*默认请求*/
    componentWillMount() {
        let config = false;
        for (var p in this.propertyMapper){
            config = true;
            break;
        }
        if (!config){
            Relay.Store.commitUpdate(
                new AllGoodsPropertyMapper({}),
                {
                    onFailure: () => {
                        console.log("请求失败")
                    },
                    onSuccess: (response) => {
                        let errorCode = response.allGoodsPropertyMapper.responseData.errorCode;
                        if (errorCode == 0) {
                            let goodsPropertyMapper = response.allGoodsPropertyMapper.responseData.goodsPropertyMapper;
                            this.propertyMapper = eval('(' + goodsPropertyMapper + ')');
                        }
                    }

                }
            );
        }
        /*一级分类*/
        this.levelRelay();
    }
    /*添加级别类型*/
    firstLevel() {
        return this.state.firstLevel.map((item, index) => {

            return <span
                key={ReactKey.key}
                className={this.isFirst === index ? "product_set_confirm1" : "product_set_confirm2"}
                onClick={this.onCheckedLevel.bind(this,index,item.categoryId,item.level)}
                ref={item.name}
            >{item.name}</span>
        })
    }
    /**/
    secondLevel() {
        return this.state.secondLevel.map((item, index) => {
            return <span
                key={ReactKey.key}
                className={this.isSecond === index ? "product_set_confirm1" : "product_set_confirm2"}
                onClick={this.onCheckedSecondLevel.bind(this,index,item.categoryId,item.level)}
                ref={item.name}
            >{item.name}</span>
        })
    }
    /*点击商品类型*/
    onCheckedLevel(indexchose,categoryId,level) {
        this.productName="";
        this.refs.search.setState({
            text:""
        });
        this.setState({
            categoryId:categoryId,
            pageNum:1
        });
        this.isFirst=indexchose;
        this.isSecond=0;
        this.categoryId=categoryId;
        this.categoryIdSender=categoryId;
        this.levelRelay(categoryId,level);
        // this.refs._selectAll.checked = false;

    }
    /**/
    onCheckedSecondLevel(indexchose,categoryId,level) {
        this.productName="";
        this.refs.search.setState({
            text:""
        });
        this.setState({
            categoryId:categoryId,
            pageNum:1
        },()=>{
            this.isSecond = indexchose;
            this.categoryId=categoryId;
            this.categoryIdSender=categoryId;
            this.levelRelay(categoryId,level);
            this.productInfoRelay(this.categoryIdSender);
        });
    }
    /*模糊搜索*/
    search() {
        this.productName = this.refs.search.state.text;
        // this.refs._selectAll.checked = false;
        this.setState({
            pageNum:1
        },()=>this.productInfoRelay(this.categoryIdSender));
    }

    /**
     * 商品编辑，删除，添加
     */
    editProduct(flag){
        let {selectedRowKeys,selectedRows} = this.state;
        switch (flag){
            case "add":
                this.refs.productBomb.showWindow(this.refs.productBomb.state.displayflag);
                break;
            case "delete":
                if(selectedRowKeys.length < 1){
                    let  message = "请勾选要操作的对象！";
                    this.refs.batchHint.showWindow(true,message);
                    break;
                }
                let  message = "确定要删除吗！";
                this.refs.batchHint.showWindow(true,message,"delete");
                break;
            case "update":
                if(selectedRowKeys.length < 1){
                    let  message = "请勾选要操作的对象！";
                    this.refs.batchHint.showWindow(true,message);
                    break;
                }
                if (selectedRowKeys.length > 1){
                    let  message = "不能批量编辑！";
                    this.refs.batchHint.showWindow(true,message);
                    return
                }
                let goodsInfo = selectedRows[0];
                this.refs.productEdit.showWindow(true,goodsInfo);
                break;
        }
    }
    //添加商品成功
    addProductSuccess(){
        this.pageInit();
        this.productInfoRelay(this.categoryIdSender);
        let this_ = this;
        Util.messageHint(this_,"success","添加成功");
        this.setState({
            successHint:false
        },()=>{
            let timer = setTimeout(()=>{
                clearTimeout(timer);
                this.setState({
                    successHint:true,
                })
            },1500);
        });
    }
    /*编辑成功*/
    updateProductSuccess(){
        // this.pageInit();
        this.setState({
            successHint:false,
            selectedRowKeys:[],
            selectedRows:[],
            pageNum:this.refs.pagination.state.text,
        },()=>{
            this.productInfoRelay(this.categoryIdSender);
            let timer = setTimeout(()=>{
                clearTimeout(timer);
                this.setState({
                    successHint:true,
                })
            },1500);
        });
    }
    /*页面表单失去焦点时*/
    bluron(type) {
        switch (type) {
            case "search":
                break;
        }
    }
    /*获取焦点*/
    focuson(type) {
        switch (type) {
            case "search":
                // this.refs._selectAll.checked = false;
                this.setState({
                    hint: "",
                });
                return;
        }
    }
    /*总页数*/
    pageTotal() {
        return Math.ceil(this.state.totalResult / this.pageSize)
    }
    /*页码*/
    onSure(size,num){
        this.setState({
            pageSize: size,
            pageNum: num,
            loading:true,
        },()=>this.productInfoRelay(this.categoryIdSender))
    }
    /**错误提示框*/
    showError(title, value) {
        Modal.warning({
            title: !title ? "提示：" : title,
            content: value,
            width: 390,
        });
    }

    /**
     * 点击产品类型的时候重置页码等信息
     */
    pageInit(){
        this.pageNum=1;
        this.setState({
            pageNum:1,
            totalResult:0,
            hint:""
        });
        this.pageItem = 0;
        this.refs.search.setState({text:""});
        this.productName="";
    }

    setCategoryMapper(goodsCatalogs){
        let length = goodsCatalogs.length;

        for (var i = 0 ; i<length ; i++){
            let goodsCatalog = goodsCatalogs[i];
            let categoryId = goodsCatalog.categoryId;
            let name = goodsCatalog.name;
            this.categoryMapper[categoryId]=name;
        }
    }
    render() {
        let columns = [
            {
                title: '序号',
                dataIndex: 'index',
                key: 'index',
                render: ((text, record, index) => {
                    return index + 1
                })
            },
        ];
        let goodsProperty = this.state.goodsProperty.split(",");
        goodsProperty.map((v,i)=>{
            let obj = {
                title: this.propertyMapper[v],
                dataIndex: v,
                key: v,
                render: (text, record) => {
                    return (
                        <span>{record[v]}</span>
                    )
                }
            };
            columns.push(obj)
        });
        let {goodsInfoDescModelList,selectedRowKeys} = this.state;
        // console.log(goodsInfoDescModelList);
        goodsInfoDescModelList = (null == goodsInfoDescModelList || goodsInfoDescModelList.length == 0) ? [] : goodsInfoDescModelList;
        const rowSelection = {
            selectedRowKeys,//默认选中项
            onChange: (selectedRowKeys, selectedRows) => {
                // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
                this.setState({
                    selectedRowKeys:selectedRowKeys,
                    selectedRows:selectedRows,
                })
            },
            getCheckboxProps: record => ({
                disabled: record.name === 'Disabled User',    // Column configuration not to be checked
            }),
        };
        return (
            <div className="product_set_box">
                <p className="product_set_title">
                    <i className="product_set_tLine"></i>
                    <span className="product_set_tText">产品分类</span>
                </p>
                <p className="product_set_tab1">一级分类：
                    {
                        this.firstLevel()
                    }
                </p>
                <p className="product_set_tab2">二级分类：
                    {
                        this.secondLevel()
                    }
                </p>
                {/*搜索*/}
                <div className="product_set_search clear">
                    <div className="product_set_searchInp">
                        <span className="product_set_searchInp_sp">品名：</span>
                        <InputBox className="product_set_searchInp_inp" space={20}
                                  defaultvalute="请输入产品名"
                                  maxlength={30} ref={'search'} bluron={this.bluron.bind(this, "search")}
                                  focuson={this.focuson.bind(this, "search")}/>
                    </div>
                    <div className="product_set_searchBtn">
                        {/*<span className="product_set_searchBtn_span" onClick={this.search.bind(this)}><i className="product_set_searchBtn_i"></i>搜索</span>*/}
                        <span className="product_set_searchBtn_span" onClick={this.search.bind(this)}>搜索</span>
                    </div>
                </div>

                <div className="product_set_bombBtn">
                    <span className="product_set_tsp2" onClick={this.editProduct.bind(this,"update")}>编辑</span>
                    <span className="product_set_tsp2" onClick={this.editProduct.bind(this,"delete")}>删除</span>
                    <span className="product_set_tsp2" onClick={this.editProduct.bind(this,"add")}>添加产品</span>
                </div>
                {/*列表*/}
                <Table
                    rowSelection={rowSelection}
                    columns={columns}
                    dataSource={goodsInfoDescModelList}
                    pagination={false}
                    rowKey={record => record.goodsId}
                    style={{width: '100%',marginTop:"10px"}}
                    className="order_table product_table"
                    scroll={{ x: 914}}
                    loading={this.state.loading}
                />
                {/*页码*/}
                <Pagination eachSize={this.state.pageSize} dataSize={this.state.totalResult} onSure={this.onSure.bind(this)} ref={'pagination'}/>

                {/*/!*操作成功提示*!/*/}
                <div className="settle_success_bg"
                     style={this.state.successHint ? {display: 'none'} : {display: 'block'}}>
                </div>
                <BatchHint ref={"batchHint"} _doDeleteProduct={this.doDeleteProduct.bind(this)}/>
                <ProductBomb ref={"productBomb"} goodsProperty={this.state.goodsProperty.split(",")} propertyMapper={this.propertyMapper} categoryMapper={this.categoryMapper}
                             categoryId={this.categoryIdSender} addSuccess={this.addProductSuccess.bind(this)} />
                <ProductEdit ref={"productEdit"} goodsProperty={this.state.goodsProperty.split(",")} propertyMapper={this.propertyMapper} categoryMapper={this.categoryMapper}
                             categoryId={this.categoryIdSender} updateSuccess={this.updateProductSuccess.bind(this)}/>
            </div>
        )
    }
}